
import MenuToggle from '../components/MenuToggle';
import FileSystemHeader from '../components/FileSystemHeader';
import { fileApi } from '@/services/api';
import React, { useEffect, useState } from 'react';
import { DialogContent, DialogTitle, DialogFooter, Dialog, DialogHeader, DialogDescription } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { http } from '@/utils/http';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { useQuery } from '@tanstack/react-query';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { SelectItem, Select, SelectContent, SelectValue, SelectTrigger } from '@/components/ui/select';
import FilePreviewGrid from '../components/FilePreviewGrid';
import { RefreshCw, Grid, MoreVertical, Upload, Repeat, AlertTriangle, ChevronRight, Eye, Trash2, Filter, Star, Search, ArrowLeft, List, Share2, ArrowUpDown, Home, Download, FolderPlus, Edit } from 'lucide-react';
import FileIcon from '../components/FileIcon';
import FilePreviewDialog from '../components/FilePreviewDialog';
import { DropdownMenuItem, DropdownMenuTrigger, DropdownMenuContent, DropdownMenu } from '@/components/ui/dropdown-menu';
import FileUploadDialog from '../components/FileUploadDialog';
import FileRenameDialog from '../components/FileRenameDialog';
import { Button } from '@/components/ui/button';

// 根据文件名判断文件类型
const getFileType = (fileName) => {
  const extension = fileName.split('.').pop()?.toLowerCase();
  
  if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(extension)) {
    return 'image';
  } else if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv'].includes(extension)) {
    return 'video';
  } else if (['mp3', 'wav', 'flac', 'aac', 'ogg'].includes(extension)) {
    return 'audio';
  } else if (['pdf'].includes(extension)) {
    return 'pdf';
  } else if (['doc', 'docx'].includes(extension)) {
    return 'document';
  } else if (['xls', 'xlsx'].includes(extension)) {
    return 'spreadsheet';
  } else if (['ppt', 'pptx'].includes(extension)) {
    return 'presentation';
  } else if (['zip', 'rar', '7z', 'tar', 'gz'].includes(extension)) {
    return 'archive';
  } else if (['js', 'jsx', 'ts', 'tsx', 'html', 'css', 'json', 'xml', 'py', 'java', 'cpp', 'c'].includes(extension)) {
    return 'code';
  } else if (['exe', 'msi', 'dmg', 'deb', 'rpm'].includes(extension)) {
    return 'executable';
  } else if (['fig'].includes(extension)) {
    return 'figma';
  } else {
    return 'file';
  }
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes || bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-';
  try {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    });
  } catch (error) {
    return dateString;
  }
};

const MyFile = ({ toggleSidebar }) => {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const sourceId = searchParams.get('sourceId');
  const filePathParam = searchParams.get('filePath');
  
  const [viewMode, setViewMode] = useState('list');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedFiles, setSelectedFiles] = useState([]);
  const [currentPath, setCurrentPath] = useState(filePathParam || '/');
  const [currentStorageSource, setCurrentStorageSource] = useState(null);
  const [showUploadDialog, setShowUploadDialog] = useState(false);
  const [showPreviewDialog, setShowPreviewDialog] = useState(false);
  const [previewFile, setPreviewFile] = useState(null);
  const [showCreateFolderDialog, setShowCreateFolderDialog] = useState(false);
  const [newFolderName, setNewFolderName] = useState('');
  const [isCreatingFolder, setIsCreatingFolder] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [fileToDelete, setFileToDelete] = useState(null);
  const [isDeleting, setIsDeleting] = useState(false);
  const [showRenameDialog, setShowRenameDialog] = useState(false);
  const [fileToRename, setFileToRename] = useState(null);

  // 检测是否为移动设备
  const isMobileDevice = () => {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth < 768;
  };

  // 获取带 token 的预览 URL
  const getPreviewUrlWithToken = (previewUrl) => {
    if (!previewUrl) return null;
    
    const token = localStorage.getItem('authToken') || sessionStorage.getItem('authToken');
    if (!token) return previewUrl;
    
    const separator = previewUrl.includes('?') ? '&' : '?';
    return `${previewUrl}${separator}accessToken=${token}`;
  };

  // 同步 currentPath 到 URL 参数
  useEffect(() => {
    if (sourceId) {
      const newParams = new URLSearchParams(searchParams);
      newParams.set('filePath', currentPath);
      setSearchParams(newParams, { replace: true });
    }
  }, [currentPath, sourceId]);

  // 从 URL 参数初始化 currentPath
  useEffect(() => {
    if (filePathParam && filePathParam !== currentPath) {
      setCurrentPath(filePathParam);
    }
  }, [filePathParam]);

  // 获取文件列表
  const { data: filesData, isLoading, error, refetch } = useQuery({
    queryKey: ['files', sourceId, currentPath],
    queryFn: async () => {
      if (!sourceId) {
        throw new Error('未选择存储源');
      }
      
      const response = await http.post('/storage/stg-file/list', {
        sourceId: parseInt(sourceId),
        currentPath: currentPath
      });
      
      if (response.code === "200" && response.msg === "success") {
        return response.data || [];
      } else {
        throw new Error(response.msg || '获取文件列表失败');
      }
    },
    enabled: !!sourceId,
    retry: 2,
    staleTime: 30000
  });

  // 转换API数据为组件需要的格式
  const files = React.useMemo(() => {
    if (!filesData) return [];
    
    return filesData.map(file => {
      const isDirectory = file.fileType === 'directory';
      
      return {
        id: file.fileId,
        name: file.fileName,
        type: isDirectory ? 'folder' : getFileType(file.fileName),
        size: formatFileSize(file.fileSize),
        modified: formatDate(file.lastUpdatedAt),
        path: file.filePath,
        hashCode: file.hashCode,
        status: file.status,
        previewUrl: file.previewUrl,
        fileUrl: file.fileUrl,
        isDirectory: isDirectory,
        fileKey: file.fileKey
      };
    });
  }, [filesData]);

  useEffect(() => {
    if (sourceId) {
      // 获取存储源信息
      const fetchStorageSource = async () => {
        try {
          const response = await http.get('/storage/stg-source/self');
          if (response.code === "200" && response.msg === "success" && response.data) {
            const source = response.data.find(s => s.sourceId === parseInt(sourceId));
            if (source) {
              setCurrentStorageSource(source);
            }
          }
        } catch (error) {
          console.error('获取存储源信息失败:', error);
        }
      };
      
      fetchStorageSource();
    }
  }, [sourceId]);

  const filteredFiles = files.filter(file => {
    const matchesSearch = file.name.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesSearch;
  });

  // 修复：确保文件选中功能正常工作
  const handleFileSelect = (fileId, event) => {
    // 阻止事件冒泡
    if (event) {
      event.stopPropagation();
    }
    
    setSelectedFiles(prev => {
      if (prev.includes(fileId)) {
        return prev.filter(id => id !== fileId);
      } else {
        return [...prev, fileId];
      }
    });
  };

  const handleFolderOpen = (file) => {
    if (file.isDirectory) {
      const newPath = currentPath === '/' 
        ? `/${file.name}` 
        : `${currentPath}/${file.name}`;
      
      setCurrentPath(newPath);
      setSelectedFiles([]);
    }
  };

  // 新增：处理面包屑点击事件
  const handleBreadcrumbClick = (pathSegment) => {
    setCurrentPath(pathSegment);
    setSelectedFiles([]);
  };

  // 新增：解析当前路径为面包屑数组
  const getBreadcrumbSegments = () => {
    if (currentPath === '/') {
      return [{ name: '根目录', path: '/' }];
    }
    
    const segments = currentPath.split('/').filter(Boolean);
    const breadcrumbs = [{ name: '根目录', path: '/' }];
    
    let accumulatedPath = '';
    segments.forEach(segment => {
      accumulatedPath += `/${segment}`;
      breadcrumbs.push({
        name: segment,
        path: accumulatedPath
      });
    });
    
    return breadcrumbs;
  };

  const handleUpload = () => {
    setShowUploadDialog(true);
  };

  const handleBackToSourceChoice = () => {
    navigate('/storage/source-choice');
  };

  const handleRefresh = async () => {
    setIsRefreshing(true);
    try {
      await refetch();
    } finally {
      // 延迟一点时间让动画更明显
      setTimeout(() => {
        setIsRefreshing(false);
      }, 500);
    }
  };

  const handleUploadComplete = () => {
    refetch();
  };

  // 修改后的预览处理函数：根据设备类型采用不同策略
  const handlePreviewFile = (file) => {
    if (file.isDirectory) {
      return;
    }

    // 移动端：直接在新页面打开预览链接
    if (isMobileDevice()) {
      if (file.previewUrl) {
        const previewUrlWithToken = getPreviewUrlWithToken(file.previewUrl);
        window.open(previewUrlWithToken, '_blank', 'noopener,noreferrer');
      } else {
        alert('该文件暂无预览链接');
      }
    } else {
      // 桌面端：使用对话框预览
      setPreviewFile(file);
      setShowPreviewDialog(true);
    }
  };

  const handleCreateFolder = () => {
    setNewFolderName('');
    setShowCreateFolderDialog(true);
  };

  const handleConfirmCreateFolder = async () => {
    if (!newFolderName || !newFolderName.trim()) {
      return;
    }

    if (!sourceId) {
      return;
    }

    setIsCreatingFolder(true);

    try {
      const response = await http.post('/storage/stg-file/mkdir', {
        sourceId: parseInt(sourceId),
        directoryName: newFolderName.trim(),
        parentPath: currentPath
      });

      if (response.code === "200" && response.msg === "success") {
        setShowCreateFolderDialog(false);
        setNewFolderName('');
        refetch();
      } else {
        throw new Error(response.msg || '创建目录失败');
      }
    } catch (error) {
      console.error('创建目录失败:', error);
    } finally {
      setIsCreatingFolder(false);
    }
  };

  const handleDownload = (file, event) => {
    event.stopPropagation();
    
    if (file.isDirectory) {
      return;
    }
    
    if (file.fileUrl) {
      const token = localStorage.getItem('authToken') || sessionStorage.getItem('authToken');
      
      let downloadUrl = file.fileUrl;
      if (token) {
        const separator = downloadUrl.includes('?') ? '&' : '?';
        downloadUrl = `${downloadUrl}${separator}accessToken=${token}`;
      }
      
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = file.name;
      link.style.display = 'none';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } else {
      console.warn('文件下载链接不存在:', file.name);
    }
  };

  // 新增：删除文件或目录的处理函数
  const handleDeleteFile = (file, event) => {
    event.stopPropagation();
    setFileToDelete(file);
    setShowDeleteConfirm(true);
  };

  const confirmDelete = async () => {
    if (!fileToDelete) return;

    setIsDeleting(true);
    
    try {
      const response = await fileApi.removeFiles([fileToDelete.fileKey]);
      
      if (response.code === "200" && response.msg === "success") {
        refetch();
        setSelectedFiles(prev => prev.filter(id => id !== fileToDelete.id));
        setShowDeleteConfirm(false);
        setFileToDelete(null);
      } else {
        throw new Error(response.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
    } finally {
      setIsDeleting(false);
    }
  };

  const cancelDelete = () => {
    setShowDeleteConfirm(false);
    setFileToDelete(null);
  };

  const handleRenameFile = (file, event) => {
    event.stopPropagation();
    setFileToRename(file);
    setShowRenameDialog(true);
  };

  const handleConfirmRename = async (file, newName) => {
    try {
      const response = await fileApi.renameFileOrDirectory(file.fileKey, newName);
      
      if (response.code === "200" && response.msg === "success") {
        refetch();
        alert('重命名成功');
      } else {
        throw new Error(response.msg || '重命名失败');
      }
    } catch (error) {
      console.error('重命名失败:', error);
      alert(error.message || '重命名失败，请稍后重试');
      throw error;
    }
  };

  if (!sourceId) {
    return (
      <div className="flex flex-col h-screen">
        <div className="flex-shrink-0 mt-3">
          <div className="px-4 py-4">
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-primary to-primary-600 rounded-xl flex items-center justify-center">
                  <Home className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">我的文件</h1>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div className="flex-1 overflow-auto">
          <div className="px-4 py-6 mx-[1%]">
            <div className="mb-6 p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
              <div className="flex items-center space-x-3">
                <div className="w-8 h-8 bg-yellow-100 rounded-full flex items-center justify-center">
                  <Home className="w-5 h-5 text-yellow-600" />
                </div>
                <div>
                  <p className="font-medium text-yellow-900">未选择存储源</p>
                  <p className="text-sm text-yellow-700">请先选择要访问的存储源</p>
                </div>
                <Button 
                  onClick={handleBackToSourceChoice}
                  className="ml-auto bg-yellow-600 hover:bg-yellow-700 text-white"
                >
                  选择存储源
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  const breadcrumbSegments = getBreadcrumbSegments();

  return (
    <div className="flex flex-col h-screen">
      {/* 头部工具栏 - 固定 */}
      <div className="flex-shrink-0 mt-3">
        <div className="px-4 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-primary to-primary-600 rounded-xl flex items-center justify-center">
                  <Home className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    我的文件
                  </h1>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 操作栏 - 固定 - 增加左右1%的margin */}
      <div className="flex-shrink-0">
        <div className="px-4 py-3 mx-[1%]">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
            <div className="flex items-center space-x-3">
              <Button 
                onClick={handleBackToSourceChoice}
                variant="ghost"
                className="text-blue-600 hover:text-blue-700 hover:bg-blue-50"
              >
                <Repeat className="w-4 h-4 mr-2" />
                {currentStorageSource ? currentStorageSource.sourceName : '切换存储源'}
              </Button>
            </div>

            <div className="flex items-center space-x-3">
              <div className="flex items-center bg-material-grey-100 rounded-lg p-1">
                <Button
                  variant={viewMode === 'grid' ? 'default' : 'ghost'}
                  size="sm"
                  onClick={() => setViewMode('grid')}
                  className="px-3"
                  title="卡片模式"
                >
                  <Grid className="w-4 h-4" />
                </Button>
                <Button
                  variant={viewMode === 'list' ? 'default' : 'ghost'}
                  size="sm"
                  onClick={() => setViewMode('list')}
                  className="px-3"
                  title="列表模式"
                >
                  <List className="w-4 h-4" />
                </Button>
                <Button
                  variant={viewMode === 'preview' ? 'default' : 'ghost'}
                  size="sm"
                  onClick={() => setViewMode('preview')}
                  className="px-3"
                  title="预览模式"
                >
                  <Eye className="w-4 h-4" />
                </Button>
              </div>

              <Button
                variant="ghost"
                size="sm"
                onClick={handleRefresh}
                disabled={isLoading || isRefreshing}
                className="p-2 hover:bg-material-grey-100 active:scale-95 transition-all duration-150"
              >
                <RefreshCw className={`w-4 h-4 ${isLoading || isRefreshing ? 'animate-spin' : ''}`} />
              </Button>

              <Button
                variant="ghost"
                size="sm"
                onClick={handleCreateFolder}
                className="flex items-center space-x-2 border-0"
              >
                <FolderPlus className="w-4 h-4" />
              </Button>

              <Button onClick={handleUpload} className="hidden md:flex bg-primary hover:bg-primary-600">
                <Upload className="w-4 h-4 mr-2" />
                上传文件
              </Button>
            </div>
          </div>

          <div className="md:hidden mt-3">
            <Button onClick={handleUpload} className="w-full bg-primary hover:bg-primary-600">
              <Upload className="w-4 h-4 mr-2" />
              上传文件
            </Button>
          </div>
        </div>
      </div>

      {/* 面包屑导航 - 固定 - 增加左右1%的margin */}
      <div className="flex-shrink-0">
        <div className="px-4 py-3 mx-[1%]">
          <div className="flex items-center space-x-2 text-sm">
            {breadcrumbSegments.map((segment, index) => (
              <React.Fragment key={segment.path}>
                {index > 0 && (
                  <ChevronRight className="w-4 h-4 text-material-grey-400" />
                )}
                <button
                  onClick={() => handleBreadcrumbClick(segment.path)}
                  className={`px-2 py-1 rounded transition-colors ${
                    index === breadcrumbSegments.length - 1
                      ? 'text-primary font-medium bg-primary/10'
                      : 'text-material-grey-600 hover:text-primary hover:bg-material-grey-100'
                  }`}
                >
                  {index === 0 ? (
                    <div className="flex items-center space-x-1">
                      <Home className="w-4 h-4" />
                      <span>{segment.name}</span>
                    </div>
                  ) : (
                    segment.name
                  )}
                </button>
              </React.Fragment>
            ))}
          </div>
        </div>
      </div>

      {/* 主内容区域 - 可滚动 - 增加左右1%的margin */}
      <div className="flex-1 overflow-auto">
        <div className="px-4 pb-6 mx-[1%]">
          {isLoading && (
            <div className="flex items-center justify-center py-12">
              <div className="text-center">
                <div className="w-16 h-16 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
                <p className="text-material-grey-600">正在加载文件列表...</p>
              </div>
            </div>
          )}

          {error && (
            <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
              <div className="flex items-center space-x-3">
                <div className="w-8 h-8 bg-red-100 rounded-full flex items-center justify-center">
                  <Trash2 className="w-5 h-5 text-red-600" />
                </div>
                <div>
                  <p className="font-medium text-red-900">加载失败</p>
                  <p className="text-sm text-red-700">{error.message}</p>
                </div>
                <Button 
                  onClick={handleRefresh}
                  className="ml-auto bg-red-600 hover:bg-red-700 text-white"
                >
                  重试
                </Button>
              </div>
            </div>
          )}

          {!isLoading && !error && (
            <div className="mt-6">
              {viewMode === 'preview' ? (
                <FilePreviewGrid
                  files={filteredFiles}
                  selectedFiles={selectedFiles}
                  onFileSelect={handleFileSelect}
                  onFolderOpen={handleFolderOpen}
                  onPreviewFile={handlePreviewFile}
                  onDownload={handleDownload}
                  onDelete={handleDeleteFile}
                />
              ) : viewMode === 'grid' ? (
                <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 xl:grid-cols-8 gap-4">
                  {filteredFiles.map((file) => (
                    <div
                      key={file.id}
                      className={`file-grid-item group relative ${
                        selectedFiles.includes(file.id) ? 'ring-2 ring-primary bg-primary/5' : ''
                      }`}
                      onDoubleClick={() => handleFolderOpen(file)}
                    >
                      <div className="absolute top-2 left-2 z-20 opacity-0 group-hover:opacity-100 transition-opacity">
                        <input
                          type="checkbox"
                          checked={selectedFiles.includes(file.id)}
                          onChange={(e) => handleFileSelect(file.id, e)}
                          onClick={(e) => e.stopPropagation()}
                          className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50 cursor-pointer"
                        />
                      </div>

                      <div className="flex flex-col items-center text-center pt-6">
                        <div className="mb-3">
                          <FileIcon type={file.type} size="large" />
                        </div>

                        <div className="w-full">
                          <p className="text-sm font-medium text-material-grey-800 truncate mb-1">
                            {file.name}
                          </p>
                          
                          <div className="text-xs text-material-grey-500">
                            <span>{file.size}</span>
                          </div>
                          
                          <div className="text-xs text-material-grey-400 mt-1">
                            {file.modified}
                          </div>
                        </div>
                      </div>

                      <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/20 rounded-lg z-10">
                        <div className="grid grid-cols-2 gap-2">
                          {!file.isDirectory && (
                            <Button
                              size="lg"
                              variant="secondary"
                              className="h-10 w-10 p-0 bg-white/90 hover:bg-white shadow-lg"
                              onClick={(e) => {
                                e.stopPropagation();
                                handlePreviewFile(file);
                              }}
                              title="预览文件"
                            >
                              <Eye className="w-5 h-5" />
                            </Button>
                          )}
                          
                          {!file.isDirectory && (
                            <Button
                              size="lg"
                              variant="secondary"
                              className="h-10 w-10 p-0 bg-white/90 hover:bg-white shadow-lg"
                              onClick={(e) => handleDownload(file, e)}
                              title="下载文件"
                            >
                              <Download className="w-5 h-5" />
                            </Button>
                          )}
                          
                          <Button
                            size="lg"
                            variant="secondary"
                            className="h-10 w-10 p-0 bg-white/90 hover:bg-white shadow-lg"
                            onClick={(e) => {
                              e.stopPropagation();
                            }}
                            title="分享文件"
                          >
                            <Share2 className="w-5 h-5" />
                          </Button>
                          
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button
                                size="lg"
                                variant="secondary"
                                className="h-10 w-10 p-0 bg-white/90 hover:bg-white shadow-lg"
                                onClick={(e) => e.stopPropagation()}
                                title="更多操作"
                              >
                                <MoreVertical className="w-5 h-5" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuItem
                                onClick={(e) => handleRenameFile(file, e)}
                              >
                                <Edit className="w-4 h-4 mr-2" />
                                重命名
                              </DropdownMenuItem>
                              <DropdownMenuItem
                                onClick={(e) => handleDeleteFile(file, e)}
                                className="text-red-600 focus:text-red-600"
                              >
                                <Trash2 className="w-4 h-4 mr-2" />
                                删除
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </div>
                      </div>

                      <div className="absolute inset-0 bg-primary/5 opacity-0 group-hover:opacity-100 transition-opacity rounded-lg pointer-events-none" />
                    </div>
                  ))}
                </div>
              ) : (
                <div className="bg-white rounded-lg shadow-material-1 overflow-hidden">
                  <div className="bg-material-grey-50 border-b border-material-grey-200 px-4 py-3">
                    <div className="flex items-center">
                      <div className="w-8"></div>
                      <div className="flex-1 grid grid-cols-12 gap-4 text-sm font-medium text-material-grey-700">
                        <div className="col-span-8 md:col-span-8">名称</div>
                        <div className="col-span-2 hidden md:block">大小</div>
                        <div className="col-span-4 md:col-span-2 text-right">操作</div>
                      </div>
                    </div>
                  </div>

                  <div className="divide-y divide-material-grey-200">
                    {filteredFiles.map((file) => (
                      <div
                        key={file.id}
                        className={`file-list-item ${
                          selectedFiles.includes(file.id) ? 'bg-primary/5' : ''
                        }`}
                        onDoubleClick={() => handleFolderOpen(file)}
                      >
                        <div className="w-8 flex-shrink-0">
                          <input
                            type="checkbox"
                            checked={selectedFiles.includes(file.id)}
                            onChange={(e) => handleFileSelect(file.id, e)}
                            onClick={(e) => e.stopPropagation()}
                            className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50 cursor-pointer"
                          />
                        </div>

                        <div className="flex-1 grid grid-cols-12 gap-4 items-center">
                          <div className="col-span-8 md:col-span-8 flex items-center space-x-3">
                            <FileIcon type={file.type} size="small" />
                            <div>
                              <p className="text-sm font-medium text-material-grey-800">
                                {file.name}
                              </p>
                            </div>
                          </div>

                          <div className="col-span-2 hidden md:block">
                            <span className="text-sm text-material-grey-600">
                              {file.size}
                            </span>
                          </div>

                          <div className="col-span-4 md:col-span-2 flex justify-end space-x-2">
                            <div className="md:hidden">
                              <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                  <Button 
                                    variant="ghost" 
                                    size="sm"
                                    onClick={(e) => e.stopPropagation()}
                                  >
                                    <MoreVertical className="w-4 h-4" />
                                  </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="end">
                                  {!file.isDirectory && (
                                    <DropdownMenuItem
                                      onClick={(e) => {
                                        e.stopPropagation();
                                        handlePreviewFile(file);
                                      }}
                                    >
                                      <Eye className="w-4 h-4 mr-2" />
                                      预览
                                    </DropdownMenuItem>
                                  )}
                                  {!file.isDirectory && (
                                    <DropdownMenuItem
                                      onClick={(e) => handleDownload(file, e)}
                                    >
                                      <Download className="w-4 h-4 mr-2" />
                                      下载
                                    </DropdownMenuItem>
                                  )}
                                  <DropdownMenuItem
                                    onClick={(e) => e.stopPropagation()}
                                  >
                                    <Share2 className="w-4 h-4 mr-2" />
                                    分享
                                  </DropdownMenuItem>
                                  <DropdownMenuItem
                                    onClick={(e) => handleRenameFile(file, e)}
                                  >
                                    <Edit className="w-4 h-4 mr-2" />
                                    重命名
                                  </DropdownMenuItem>
                                  <DropdownMenuItem
                                    onClick={(e) => handleDeleteFile(file, e)}
                                    className="text-red-600 focus:text-red-600"
                                  >
                                    <Trash2 className="w-4 h-4 mr-2" />
                                    删除
                                  </DropdownMenuItem>
                                </DropdownMenuContent>
                              </DropdownMenu>
                            </div>

                            <div className="hidden md:flex md:space-x-2">
                              {!file.isDirectory && (
                                <Button 
                                  variant="ghost" 
                                  size="sm"
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    handlePreviewFile(file);
                                  }}
                                  title="预览文件"
                                >
                                  <Eye className="w-4 h-4" />
                                </Button>
                              )}
                              
                              {!file.isDirectory && (
                                <Button 
                                  variant="ghost" 
                                  size="sm"
                                  onClick={(e) => handleDownload(file, e)}
                                  title="下载文件"
                                >
                                  <Download className="w-4 h-4" />
                                </Button>
                              )}
                              
                              <Button 
                                variant="ghost" 
                                size="sm"
                                onClick={(e) => e.stopPropagation()}
                              >
                                <Share2 className="w-4 h-4" />
                              </Button>
                              
                              <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                  <Button 
                                    variant="ghost" 
                                    size="sm"
                                    onClick={(e) => e.stopPropagation()}
                                  >
                                    <MoreVertical className="w-4 h-4" />
                                  </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="end">
                                  <DropdownMenuItem
                                    onClick={(e) => handleRenameFile(file, e)}
                                  >
                                    <Edit className="w-4 h-4 mr-2" />
                                    重命名
                                  </DropdownMenuItem>
                                  <DropdownMenuItem
                                    onClick={(e) => handleDeleteFile(file, e)}
                                    className="text-red-600 focus:text-red-600"
                                  >
                                    <Trash2 className="w-4 h-4 mr-2" />
                                    删除
                                  </DropdownMenuItem>
                                </DropdownMenuContent>
                              </DropdownMenu>
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          {!isLoading && !error && filteredFiles.length === 0 && (
            <div className="text-center py-12">
              <div className="w-24 h-24 mx-auto mb-4 bg-material-grey-200 rounded-full flex items-center justify-center">
                <Home className="w-8 h-8 text-material-grey-500" />
              </div>
              <h3 className="text-lg font-medium text-material-grey-700 mb-2">
                {searchQuery ? '未找到匹配的文件' : '文件夹为空'}
              </h3>
              <p className="text-material-grey-500 mb-4">
                {searchQuery ? '尝试使用不同的关键词搜索' : '开始上传您的第一个文件'}
              </p>
              {!searchQuery && (
                <Button onClick={handleUpload} className="bg-primary hover:bg-primary-600">
                  <Upload className="w-4 h-4 mr-2" />
                  上传文件
                </Button>
              )}
            </div>
          )}
        </div>
      </div>

      <FileUploadDialog
        open={showUploadDialog}
        onOpenChange={setShowUploadDialog}
        sourceId={sourceId}
        currentPath={currentPath}
        onUploadComplete={handleUploadComplete}
      />

      <FilePreviewDialog
        open={showPreviewDialog}
        onOpenChange={setShowPreviewDialog}
        file={previewFile}
        previewUrl={previewFile?.previewUrl}
      />

      <Dialog open={showCreateFolderDialog} onOpenChange={setShowCreateFolderDialog}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>新建目录</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label htmlFor="folderName">目录名称</Label>
              <Input
                id="folderName"
                value={newFolderName}
                onChange={(e) => setNewFolderName(e.target.value)}
                placeholder="请输入目录名称"
                onKeyPress={(e) => {
                  if (e.key === 'Enter') {
                    handleConfirmCreateFolder();
                  }
                }}
              />
            </div>
            <div className="text-sm text-material-grey-600">
              <p>当前路径：{currentPath}</p>
            </div>
          </div>
          <DialogFooter>
            <Button 
              variant="outline" 
              onClick={() => setShowCreateFolderDialog(false)}
              disabled={isCreatingFolder}
            >
              取消
            </Button>
            <Button 
              onClick={handleConfirmCreateFolder}
              disabled={isCreatingFolder || !newFolderName.trim()}
            >
              {isCreatingFolder ? (
                <>
                  <div className="w-4 h-4 mr-2 border-2 border-white border-t-transparent rounded-full animate-spin" />
                  创建中...
                </>
              ) : (
                '确定'
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center space-x-2">
              <AlertTriangle className="w-5 h-5 text-red-600" />
              <span>确认删除</span>
            </DialogTitle>
            <DialogDescription>
              {fileToDelete && (
                <div className="mt-4 space-y-3">
                  <p className="text-material-grey-700">
                    确定要删除{fileToDelete.isDirectory ? '目录' : '文件'}吗？
                  </p>
                  <div className="p-3 bg-material-grey-50 rounded-lg border border-material-grey-200">
                    <p className="text-sm font-medium text-material-grey-900 break-all">
                      {fileToDelete.name}
                    </p>
                  </div>
                  <p className="text-red-600 text-sm font-medium">
                    此操作无法撤销！
                  </p>
                </div>
              )}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="flex-col sm:flex-row gap-2">
            <Button 
              variant="outline" 
              onClick={cancelDelete}
              disabled={isDeleting}
              className="w-full sm:w-auto"
            >
              取消
            </Button>
            <Button 
              variant="destructive"
              onClick={confirmDelete}
              disabled={isDeleting}
              className="w-full sm:w-auto"
            >
              {isDeleting ? (
                <>
                  <div className="w-4 h-4 mr-2 border-2 border-white border-t-transparent rounded-full animate-spin" />
                  删除中...
                </>
              ) : (
                <>
                  <Trash2 className="w-4 h-4 mr-2" />
                  删除
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <FileRenameDialog
        open={showRenameDialog}
        onOpenChange={setShowRenameDialog}
        file={fileToRename}
        onRename={handleConfirmRename}
      />
    </div>
  );
};

export default MyFile;

